package com.zpc.myvideoserver.service;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * @ClassName : UploadLocalService  //类名
 * @Description : 上传文件服务类  //描述
 * @Author : zpc20 //作者
 * @Date: 2023/10/25  18:31
 */
@Service
public class UploadFileService {
    @Value("${qiNiu.bucketName}")
    private String bucketName;
    @Resource
    private Auth auth;

    @Resource
    private UploadManager uploadManager;

    public boolean upload(MultipartFile file, String  filePath) {
        // 配置区域
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        cfg.resumableUploadMaxConcurrentTaskCount = 2;
        //并发上传
        // 上传管理
        // UploadManager uploadManager = new UploadManager(cfg);
        //本地上传路径
        // String localPath ="L:\\upload\\demo.mp4";
        // 文件名称
        // String key ="myvideo/video/demo.mp4";
        // Token

//        System.out.println(uploadToken);
//         String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucketName).toString();
        //设置断点续传文件进度保存目录
        // FileRecorder fileRecorder = new FileRecorder(localTempDir);
        // UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
        try {
            // 获取token
            String uploadToken = auth.uploadToken(bucketName);
            // 发送请求
            Response response = uploadManager.put(file.getInputStream(), filePath, uploadToken, null, null);
            // 解析成功结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            if (response.statusCode == 200) {
                return true;
            }
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignoreed) {

                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return false;
    }


}
